package com.example.redisson.controller;

import com.example.redisson.service.TestLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;

@RestController
@RequestMapping("/redisson")
@Slf4j
public class RedissonLockController {
  @Resource
  private TestLockService testLockService;


  /** 模拟线程数 */
  private static int threadNum = 10;

  /**
   * 模拟并发测试加锁和不加锁
   *
   * @return
   */
  @GetMapping("/test")
  public void lock() {
    // 计数器
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    for (int i = 0; i < threadNum; i++) {
      new Thread(()->{
        try {
          countDownLatch.await();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        testLockService.testCount();
        testLockService.testLockCount();
      }).start();
    }
    // 释放所有线程
    countDownLatch.countDown();
  }




}
